﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace LightEngine
{
    namespace Utilities
    {
        namespace ApplicationAssembly
        {
            public class DLLLoader
            {
                [DllImport("kernel32")]
                private static extern IntPtr LoadLibraryEx(String DllFilePath, IntPtr FileHandle, UInt32 Flags);

                [DllImport("kernel32")]
                private extern static bool FreeLibrary(IntPtr DllHandle);

                [DllImport("kernel32", CharSet = CharSet.Ansi)]
                private extern static IntPtr GetProcAddress(IntPtr DLLHandle, String FunctionName);

                public static IntPtr LoadDLL(String DllFilePath, UInt32 DllLoadingFlags)
                {
                    IntPtr DllHandle;
                    try
                    {
                        DllHandle = LoadLibraryEx(DllFilePath, IntPtr.Zero, DllLoadingFlags);
                        return DllHandle;
                    }
                    catch (Exception AnyException)
                    {
                        AnyException.ToString();
                        return IntPtr.Zero;
                    }
                }

                public static void UnLoadDll(IntPtr DllHandle)
                {
                    if (DllHandle != IntPtr.Zero)
                        FreeLibrary(DllHandle);
                }

                public static IntPtr GetFunctionAddress(IntPtr DllHandle, String FunctionName)
                {
                    IntPtr FuncAddress;
                    if (DllHandle != IntPtr.Zero)
                    {
                        FuncAddress = GetProcAddress(DllHandle, FunctionName);
                        return FuncAddress;
                    }
                    return IntPtr.Zero;
                }
            }
        }
    }
}
